package com.fyy.zookeeper.anli;

import org.apache.zookeeper.*;

/**
 * @Author fyy
 * @Description 服务器端实现
 * @Date 2020/11/12 9:48
 */
public class ZKServer {

    private static String connectString = "host1:2181,host2:2181,host3:2181"; //ZK集群
    private static int sessionTimeout = 2000; //会话过期时间2s,单位：ms
    private static ZooKeeper zkClient;

    public static void main(String[] args) throws Exception {
        ZKServer zkServer = new ZKServer();

        //连接ZK集群
        zkServer.getConnect();
        //注册节点
        zkServer.registNode(args[0]);
        //业务处理
        zkServer.business();
    }

    /**
     * @Author fyy
     * @Description 连接ZK集群
     * @Date 2020/11/12 9:52
     */
    private void getConnect() throws Exception {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {

            }
        });
    }

    /**
     * @Author fyy
     * @Description 注册节点
     * @Date 2020/11/12 9:52
     */
    private void registNode(String hostname) throws KeeperException, InterruptedException {
        String path = zkClient.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is online,The node is " + path);
    }

    /**
     * @Author fyy
     * @Description 业务处理
     * @Date 2020/11/12 9:52
     */
    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

}
